package com.yunquan.ohana.ui.weather.search

import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.view.View
import android.view.inputmethod.EditorInfo
import androidx.activity.result.ActivityResult
import androidx.core.content.ContextCompat
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsControllerCompat
import com.google.gson.Gson
import com.yunquan.ohana.BR
import com.yunquan.ohana.R
import com.yunquan.ohana.base.ui.BaseActivity
import com.yunquan.ohana.databinding.ActivityWeatherSearchBinding
import com.yunquan.ohana.ui.weather.search.adapter.WeatherSearchAdapter
import com.yunquan.ohana.utils.StringUtils
import com.yunquan.ohana.utils.ToastUtils
import com.yunquan.ohana.utils.Utils
import java.util.Locale

class WeatherSearchActivity : BaseActivity<ActivityWeatherSearchBinding, WeatherSearchViewModel>() {
    override fun initContentView(savedInstanceState: Bundle?): Int {
        return R.layout.activity_weather_search
    }

    override fun initVariableId(): Int {
        return BR.weatherSearchViewModel
    }

    override fun initParam() {
        super.initParam()
        Locale.setDefault(Locale("en"))
        // 设置背景颜色
        window.statusBarColor = ContextCompat.getColor(this, R.color.white)
        // 设置文字颜色（true = 黑色文字，false = 白色文字）
        val controller = WindowInsetsControllerCompat(window, window.decorView)
        controller.isAppearanceLightStatusBars = true
    }

    override fun initData(savedInstanceState: Bundle?) {
        super.initData(savedInstanceState)
        binding!!.adapter = WeatherSearchAdapter()
        val bundle = intent.extras
        bundle?.let {
            viewModel!!.cityName.set(it.getString("city"))
        }
    }

    override fun initViewObservable() {
        super.initViewObservable()
        viewModel!!.changeCity.observe(this) {
            val intent = intent
            intent.putExtra("city", Gson().toJson(it))
            setResult(RESULT_OK, intent)
            finish()
        }
        // 设置搜索监听
        binding!!.etInput.setOnEditorActionListener { view, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                Utils.instance.hideKeyboard(view)
                // 发送请求
                val input = view.text.toString().trim()
                if (input.isEmpty()) {
                    ToastUtils.showShort(R.string.please_input_title)
                } else {
                    // 查询数据
                    viewModel!!.searchCity(input)
                }
                true
            } else {
                false
            }
        }
    }
}